import tkinter as tk
from tkinter import filedialog
from swagger2word import swagger2word

def on_select():
    # 根据选择更新输入框的提示信息
    if var.get() == 'a':
        entry.config(state=tk.NORMAL)
        entry.delete(0, tk.END)
        # entry.insert(0, "请输入浏览器地址")
        file_button.pack_forget()  # 隐藏文件选择按钮
    else:
        entry.config(state=tk.NORMAL)
        entry.delete(0, tk.END)
        # entry.insert(0, "请点击浏览选择文件")
        file_button.pack(side=tk.RIGHT, padx=5)  # 显示文件选择按钮

def browse_file():
    # 打开文件选择对话框
    filename = filedialog.askopenfilename()
    entry.delete(0, tk.END)
    entry.insert(0, filename)

def submit():
    # 获取输入框中的值并打印
    value = entry.get()
    print("您输入的地址或文件路径为:", value)
    status_label.config(text="生成中...")
    submit_button.config(state=tk.DISABLED)
    root.update_idletasks()
    try:
        output_word_path = swagger2word(value)
        print(f"文档已保存至: {output_word_path}")
        status_label.config(text=f"已成功生成：{output_word_path}")
    except Exception as e:
        print(e)
        status_label.config(text=f"生成失败：{e}")
    submit_button.config(state=tk.NORMAL)


if __name__ == '__main__':
    # 创建主窗口
    root = tk.Tk()
    root.title("swagger2word")

    # 固定窗口大小
    root.minsize(400, 200)
    root.maxsize(400, 200)

    # 单选框变量
    var = tk.StringVar()

    # 单选框
    radio_a = tk.Radiobutton(root, text="接口地址", variable=var, value='a', command=on_select)
    radio_b = tk.Radiobutton(root, text="本地文件", variable=var, value='b', command=on_select)
    radio_a.pack(anchor=tk.W)
    radio_b.pack(anchor=tk.W)

    # 输入框和文件选择按钮的框架
    entry_frame = tk.Frame(root)
    entry = tk.Entry(entry_frame, width=50)  # 调整输入框的宽度
    entry.pack(side=tk.LEFT, pady=10, padx=5)

    # 文件选择按钮（仅在选择了b时有效）
    file_button = tk.Button(entry_frame, text="浏览", command=browse_file)
    file_button.pack_forget()  # 初始隐藏文件选择按钮

    # 将输入框和文件选择按钮放在同一个框架中
    entry_frame.pack(pady=5)

    # 提交按钮
    submit_button = tk.Button(root, text="开始", command=submit)
    submit_button.pack(pady=10)

    # 状态标签
    status_label = tk.Label(root, text="")
    status_label.pack(pady=5)

    # 初始化单选框状态
    var.set('a')
    on_select()

    # 运行主循环
    root.mainloop()